from flask import Blueprint, render_template, request, session, redirect, url_for, flash, jsonify, make_response, g
from models import Users
from .forms import LoginForm
from decorators import login_required

bp = Blueprint('user', __name__, url_prefix='/user')


@bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    else:
        form = LoginForm(request.form)
        if form.validate():
            username = form.username.data
            password = form.password.data
            user = Users.query.filter_by(username=username).first()
            if user and user.password == password:
                session['user_id'] = user.id
                g.user = user
                return jsonify({'success': True})
            else:
                return jsonify({'success': False, "msg": '账号和密码不匹配!'})
        else:
            return jsonify({'success': False, "msg": '账号或密码格式不正确!'})


@bp.route('/home')
@login_required
def home():
    return render_template('home.html')


@bp.route('/logout')
def logout():
    session.clear()
    return render_template('login.html')
